/**
 * 性能监控中间件
 * Performance Monitoring Middleware
 */

const { performanceMonitor } = require('../utils/performance');
const logger = require('../utils/logger');
const config = require('../config/config');

/**
 * 请求性能监控中间件
 */
function requestPerformanceMiddleware(req, res, next) {
  if (!config.performance?.enableMonitoring) {
    return next();
  }

  const startTime = Date.now();
  const startMemory = process.memoryUsage();

  // 监听响应完成事件
  res.on('finish', () => {
    const responseTime = Date.now() - startTime;
    const endMemory = process.memoryUsage();
    const success = res.statusCode < 400;

    // 记录请求指标
    performanceMonitor.recordRequest(responseTime, success);

    // 记录详细的请求信息（仅对慢请求）
    if (responseTime > (config.performance?.alertThresholds?.responseTime || 5000)) {
      logger.warn('慢请求检测 / Slow request detected', {
        method: req.method,
        url: req.originalUrl,
        responseTime: responseTime + 'ms',
        statusCode: res.statusCode,
        userAgent: req.get('User-Agent'),
        ip: req.ip,
        memoryDelta: {
          heapUsed: endMemory.heapUsed - startMemory.heapUsed,
          heapTotal: endMemory.heapTotal - startMemory.heapTotal,
          external: endMemory.external - startMemory.external
        }
      });
    }

    // 记录调试信息（仅在debug级别）
    logger.debug('请求完成 / Request completed', {
      method: req.method,
      url: req.originalUrl,
      responseTime: responseTime + 'ms',
      statusCode: res.statusCode,
      contentLength: res.get('Content-Length') || 0
    });
  });

  next();
}

/**
 * 系统资源监控中间件
 */
function systemResourceMiddleware(req, res, next) {
  if (!config.performance?.enableMonitoring) {
    return next();
  }

  // 检查系统资源使用情况
  const metrics = performanceMonitor.getMetrics();
  
  // 如果内存使用率过高，记录警告
  if (metrics.memory.percentage > (config.performance?.alertThresholds?.memoryUsage || 80)) {
    logger.warn('高内存使用率警告 / High memory usage warning', {
      memoryUsage: metrics.memory.percentage.toFixed(1) + '%',
      heapUsed: (metrics.memory.heap.used / 1024 / 1024).toFixed(2) + 'MB',
      heapTotal: (metrics.memory.heap.total / 1024 / 1024).toFixed(2) + 'MB',
      url: req.originalUrl,
      method: req.method
    });
  }

  // 如果CPU使用率过高，记录警告
  if (metrics.cpu.usage > (config.performance?.alertThresholds?.cpuUsage || 80)) {
    logger.warn('高CPU使用率警告 / High CPU usage warning', {
      cpuUsage: metrics.cpu.usage.toFixed(1) + '%',
      loadAverage: metrics.cpu.loadAverage,
      url: req.originalUrl,
      method: req.method
    });
  }

  next();
}

/**
 * 性能指标API端点
 */
function performanceMetricsHandler(req, res) {
  try {
    const report = performanceMonitor.getPerformanceReport();
    const logStats = logger.getLogStats();
    
    // 获取数据库连接状态
    const { getStatus: getDbStatus } = require('../database/connection');
    const dbStatus = getDbStatus();

    res.json({
      success: true,
      data: {
        performance: report,
        database: dbStatus,
        logging: logStats,
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    logger.error('获取性能指标失败 / Failed to get performance metrics', {
      error: error.message
    });
    
    res.status(500).json({
      success: false,
      message: '获取性能指标失败 / Failed to get performance metrics'
    });
  }
}

/**
 * 重置性能指标API端点
 */
function resetMetricsHandler(req, res) {
  try {
    performanceMonitor.resetMetrics();
    
    res.json({
      success: true,
      message: '性能指标已重置 / Performance metrics reset successfully'
    });
  } catch (error) {
    logger.error('重置性能指标失败 / Failed to reset performance metrics', {
      error: error.message
    });
    
    res.status(500).json({
      success: false,
      message: '重置性能指标失败 / Failed to reset performance metrics'
    });
  }
}

/**
 * 健康检查增强版
 */
function healthCheckHandler(req, res) {
  try {
    const metrics = performanceMonitor.getMetrics();
    const { getStatus: getDbStatus } = require('../database/connection');
    const dbStatus = getDbStatus();
    
    const health = {
      status: 'ok',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
      version: process.version,
      environment: process.env.NODE_ENV || 'development',
      memory: {
        usage: metrics.memory.percentage.toFixed(1) + '%',
        heap: {
          used: (metrics.memory.heap.used / 1024 / 1024).toFixed(2) + 'MB',
          total: (metrics.memory.heap.total / 1024 / 1024).toFixed(2) + 'MB'
        }
      },
      cpu: {
        usage: metrics.cpu.usage.toFixed(1) + '%',
        loadAverage: metrics.cpu.loadAverage
      },
      database: {
        connected: dbStatus.connected,
        activeConnections: dbStatus.activeConnections,
        totalConnections: dbStatus.totalConnections
      },
      requests: {
        total: metrics.requests.total,
        successful: metrics.requests.successful,
        failed: metrics.requests.failed,
        averageResponseTime: metrics.requests.averageResponseTime.toFixed(2) + 'ms'
      }
    };

    // 检查系统健康状态
    const alerts = performanceMonitor.checkAlertThresholds();
    if (alerts.length > 0) {
      health.status = 'warning';
      health.alerts = alerts;
    }

    // 如果数据库未连接，标记为不健康
    if (!dbStatus.connected) {
      health.status = 'error';
      health.error = 'Database connection lost';
    }

    const statusCode = health.status === 'ok' ? 200 : 
                      health.status === 'warning' ? 200 : 503;

    res.status(statusCode).json(health);
  } catch (error) {
    logger.error('健康检查失败 / Health check failed', {
      error: error.message
    });
    
    res.status(503).json({
      status: 'error',
      timestamp: new Date().toISOString(),
      error: 'Health check failed'
    });
  }
}

module.exports = {
  requestPerformanceMiddleware,
  systemResourceMiddleware,
  performanceMetricsHandler,
  resetMetricsHandler,
  healthCheckHandler
};